package com.atguigu.gmall.payment.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AliPayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author gsy
 * @date 2021年09月14日14:26
 * Description 支付宝
 */
@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private PaymentInfoService paymentService;
    @Autowired
    private AlipayClient alipayClient;


    @Override
    public String submitAliPay(Long orderId) {
        //保存支付信息
        PaymentInfo paymentInfo = paymentService.savePaymentInfo(orderId, PaymentType.ALIPAY);
        //连接支付宝 下单
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradeCreateModel model = new AlipayTradeCreateModel();
        model.setOutTradeNo(paymentInfo.getOutTradeNo());
        model.setTotalAmount(paymentInfo.getTotalAmount().toString());
        model.setSubject(paymentInfo.getSubject());
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setBody(paymentInfo.getSubject());
        request.setBizModel(model);
        //同步通知用户  支付成功
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //异步通知商户
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }


}
